package ru.averta.notes.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import ru.averta.notes.domain.*;
import ru.averta.notes.domain.ajax.AjaxSiteRequest;
import ru.averta.notes.domain.ajax.AjaxSubjectCreateAnswer;
import ru.averta.notes.domain.forms.SiteAddForm;
import ru.averta.notes.other.UtilsAjax;
import ru.averta.notes.service.*;
import ru.averta.notes.service.search.SubjectCriteriaSimpleBean;
import ru.averta.notes.service.search.SubjectCriteriaSearchService;
import ru.averta.notes.service.tag.TagManager;
import ru.averta.notes.web.validators.AddSiteValidator;

import java.util.Map;

/**
 * <code>AddSubjectController</code>
 *
 * @author: fedor.belov (fedor.belov@mail.ru)
 * Date: 30.05.11 23:55
 */

/* ��� ������������ ������������


function test(){
                            var d = '{"fileId":-35722,"id":333333,"comment":"��� �����������","tags":[{"id":0,"title":"��� ������ ������"},{"id":0,"title":"� �����"}],"title":"��� ���������","folder":{"id":9910,"title":"�����","fullPath":"����/��/�����"}}';
                            $.ajax({'url':"/notes/notes/add/fileRequest/all/",
         'data':d,
         contentType: "application/json",
         'type': 'post',
         'success': function(data){ console.log(data);}
         });}


 */

@Controller
public class AddSubjectController {

    private Logger logger = LoggerFactory.getLogger(AddSubjectController.class);

    @Autowired private SubjectCriteriaSearchService criteriaSearch;
    @Autowired private SiteService siteService;
    @Autowired private AddSiteValidator siteValidator;
    @Autowired private TagManager tagManager;
    @Autowired private UtilsAjax ajax;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
//        binder.registerCustomEditor(Folder.class, new FolderEditor(folderService));
    }
    
    @RequestMapping(value = "/notes/add/site/{target}/**", method = RequestMethod.POST)
    public @ResponseBody Object addSite(
            @PathVariable String target,
            @RequestParam(required = false) String tags,
            @RequestParam(required = false) String types,
            @RequestParam(required = false) Long id,
            @RequestParam(required = false) Byte favorite,
            SiteAddForm site, BindingResult result, Map model) {

        AjaxSubjectCreateAnswer answer = new AjaxSubjectCreateAnswer();

        if (checkSiteContent(site, result, true)) {
            Site siteSubject = site.loadToDomainObject(new Site());//TODO
            siteService.create(siteSubject);
            answer.setDisplay(checkDisplay(siteSubject, target, tags, types, id, favorite));
        } else {
            loadErrors(answer, result);
        }

        return ajax.castAjax(answer, AjaxSubjectCreateAnswer.class);
    }

    /**
     * Загружает теги из запроса
     * @param subject
     * @param request
     */
    private void loadTagsFromRequest(Site subject, AjaxSiteRequest request) {
        for (String tag : request.getTags().getTags()) {
            tagManager.addTag(subject, tag);
        }
    }

    private boolean checkSiteContent(SiteAddForm subject, Errors errors, boolean isEdit) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "title.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "url", "url.empty");
        if (isEdit) ValidationUtils.rejectIfEmpty(errors, "id", "id.empty");
        return !errors.hasErrors();
    }

    private void loadErrors(AjaxSubjectCreateAnswer answer, Errors errors) {
        if (errors.hasErrors()) {
            answer.setHasErrors(true);
            answer.setGlobalErrors(ajax.castErrors(errors.getGlobalErrors()));
            answer.setFieldErrors(ajax.castFieldErrors(errors.getFieldErrors()));
        }
    }

    private boolean checkDisplay(Site subject, String target, String tags, String types, Long id, Byte favorite) {
        SubjectCriteriaSimpleBean criteria = MainDisplayController.getCriteriaForParams(target, tags, types, id, favorite);
        return criteriaSearch.checkSubjectByCriteria(subject, criteria);
    }

   
}
